/*
 * @Description:
 * @Author: william
 * @Date: 2024-08-08 14:45:49
 * @LastEditors: william
 * @LastEditTime: 2025-10-28 17:21:53
 */

import { baseURL } from './envConfig'
import { getCookieLang, getUmsToken } from '@/utils/cookies'

// utils/http.js
class Http {
  constructor(options = {}) {
    // 请求的根路径
    this.baseUrl = options.baseUrl || baseURL
    // 请求的 url 地址
    this.url = options.url || ''
    // 请求方式
    this.method = 'GET'
    // 请求的参数对象
    this.data = null
    // header 请求头
    this.header = options.header || {}
    this.beforeRequest = null
    this.afterRequest = null
  }

  // 添加对header的支持
  _mergeHeaders(customHeader = {}) {
    return Object.assign({}, this.header, customHeader) // 合并默认header和自定义header
  }

  get(url, data = {}, header = {}, options) {
    this.method = 'GET'
    g_utils.isExternal(url) ? (this.url = url) : (this.url = this.baseUrl + url)
    this.data = data
    this.header = {}
    this.header = this._mergeHeaders(header) // 合并header
    return this._(this.url, this.method, this.data, this.header, options)
  }

  post(url, data = {}, header = {}, options) {
    this.method = 'POST'
    g_utils.isExternal(url) ? (this.url = url) : (this.url = this.baseUrl + url)
    this.data = data
    this.header = {}
    this.header = this._mergeHeaders(header) // 合并header
    return this._(this.url, this.method, this.data, this.header, options)
  }

  put(url, data = {}) {
    this.method = 'PUT'
    g_utils.isExternal(url) ? (this.url = url) : (this.url = this.baseUrl + url)
    this.data = data
    this.header = {}
    return this._(this.url, this.method, this.data, this.header)
  }

  delete(url, data = {}) {
    this.method = 'DELETE'
    g_utils.isExternal(url) ? (this.url = url) : (this.url = this.baseUrl + url)
    this.data = data
    this.header = {}
    return this._(this.url, this.method, this.data, this.header)
  }

  // 查询网络状态
  checkNetwork() {
    return new Promise((resolve, reject) => {
      uni.getNetworkType({
        success: res => {
          console.log('uni.getNetworkType', res.networkType)
          res.networkType === 'none' &&
            g_utils.showToast(g_t('public.dataErrorRetry'))
          resolve(res.networkType)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }

  // 监听网络状态变化
  onNetworkStatusChange(callback) {
    uni.onNetworkStatusChange(res => {
      res.networkType === 'none' &&
        g_utils.showToast(g_t('public.dataErrorRetry'))
    })
  }

  _(url, method, data, header, options) {
    // 请求之前做一些事
    this.beforeRequest &&
      typeof this.beforeRequest === 'function' &&
      this.beforeRequest(this)
    // 发起请求
    return new Promise(async (resolve, reject) => {
      // try {
      //   const networkType = await this.checkNetwork()
      //   if (networkType === 'none') {
      //     resolve({})
      //     return
      //   }
      // } catch (err) {
      //   reject(err)
      //   return
      // }
      this.requestInterceptor(data, header)
      const logTip = {
        请求地址: url,
        请求方式: method,
        请求头: header,
        请求数据: data,
        请求时间: new Date().toLocaleString()
      }
      const showToast = data.showToast
      delete data.showToast
      console.log('请求拦截器', logTip)
      uni.request({
        url: url,
        method: method,
        data: data,
        header: header,
        sslVerify: false, // 是否验证ssl证书，仅App安卓端支持
        timeout: options?.timeout || 40 * 1000,
        success: res => {
          resolve({
            ...res.data,
            code: res.data.code * 1
          })
        },
        fail: err => {
          reject(err)
        },
        complete: res => {
          console.log('request-completeres', res)
          this.responseInterceptor(res, showToast, logTip)
          // 请求完成以后做一些事情
          this.afterRequest &&
            typeof this.afterRequest === 'function' &&
            this.afterRequest(res)
        }
      })
    })
  }
  // 请求拦截
  requestInterceptor(data, header) {
    header['lang'] = getCookieLang() === 'en' ? 'en_US' : 'zh_CN' // 添加切换语言
    header['iot-app-name'] = 'iot-pipe'
    if (data.isLogin) {
      delete data.isLogin
    } else {
      header.Authorization = 'Bearer' + ' ' + getUmsToken()
    }
  }

  // 响应拦截器
  responseInterceptor(
    { data, statusCode, errMsg },
    showToast = true,
    logTip = {}
  ) {
    console.log('响应拦截器', {
      ...logTip,
      返回数据: data || '',
      '返回状态码(statusCode)': statusCode || '',
      '错误提示(errMsg)': errMsg
    })
    uni.stopPullDownRefresh()
    if (!data) {
      if (statusCode === 500) {
        showToast && g_utils.showToast('服务器开小差了，请稍后再试')
      } else if (errMsg && showToast) {
        let errText = errMsg
        if (
          errMsg.includes('request:fail abort statusCode:-1') ||
          errMsg === 'request:fail'
        ) {
          errText = '网络异常，请检查网络是否正常！'
        } else if (errMsg === 'request:fail timeout') {
          errText = g_t('public.timeOutTip')
        }
        g_utils.showToast(errText)
      }
      return
    }
    // 判断返回状态 执行相应操作
    const code = data.code * 1
    if (statusCode !== 401 && statusCode !== 200) {
      showToast && g_utils.showToast(g_t('public.dataErrorRetry'))
    } else if (code === 401 || code === 1006 || code === 1010) {
      // token失效等情况，重定向到登录界面
      showToast && g_utils.showToast(g_t('public.loginExpired'))
      // 获取当前页面栈
      const pages = getCurrentPages()
      // 获取当前页面
      const currentPage = pages[pages.length - 1]
      // 获取当前页面的路由信息
      const route = currentPage?.route
      if (route !== 'pages/login/index') useOutsideUserStore().setLogOut()
    } else if (code !== 200) {
      showToast && g_utils.showToast(data.message)
    }
  }
}

export const http = new Http()
